package com.macro.ai.chat.controller;

import org.springframework.ai.chat.client.ChatClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.codec.ServerSentEvent;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

@RestController
//@CrossOrigin(origins = "http://localhost:8081")
public class ChatAiController {

    @Autowired
    private ChatClient chatClient;

    //角色预设，使用非流式响应
    @GetMapping("/chatai")
    public String chatAi(@RequestParam(value = "message") String message){
        return chatClient.prompt().user(message).call().content();
    }

    //角色预设，使用流式响应，逐个字符输出，注意设置格式和编码方式，不然会乱码
    @GetMapping(value = "/chataiStream", produces = "text/event-stream;charset=UTF-8")
//    @GetMapping(value = "/chataiStream", produces = "text/html;charset=UTF-8")
    public Flux<ServerSentEvent<String>> chatAiStream(@RequestParam(value = "message") String message){
        System.out.println("start");


        return chatClient.prompt().user(message).stream().content().map(token -> {
            return ServerSentEvent.builder(token).event("message").build();
        }).doOnComplete(() -> {
//            return createSingleSseEvent("end");
        });

    }

    //角色预设，使用流式响应，逐个字符输出，注意设置格式和编码方式，不然会乱码
//    @GetMapping(value = "/chataiStream", produces = "text/event-stream;charset=UTF-8")
////    @GetMapping(value = "/chataiStream", produces = "text/html;charset=UTF-8")
//    public Flux<String> chatAiStream(@RequestParam(value = "message") String message){
//        System.out.println("start");
//        return chatClient.prompt().user(message).stream().content();
//    }

    //openai版本
//    @GetMapping(value = "/submit")
//    private Flux<String> submit(HttpServletResponse response, @RequestParam String question) {
//        response.setContentType("text/event-stream;charset=utf-8");
//        openAi.setPrompt(question);
//        WebClient authorization = webClient.post()
//                .uri("https://api.openai.com/v1/completions")
//                .header("Content-Type", "application/json")
//                .header("Authorization", "Bearer " + secretKey)
//                .bodyValue(JSON.toJSONString(openAi))
//                .retrieve();
//        Flux<String> stringFlux = authorization.bodyToFlux(String.class);
//        return stringFlux.mapNotNull(string -> {
//            //openai中回复结束会带DONE标识
//            if (string.contains("DONE")) {
//                return "Answer Done!";
//            }
//            Answer answer = JSON.parseObject(string, Answer.class);
//            StringBuilder stringBuilder = new StringBuilder();
//            List<Choices> choices = answer.getChoices();
//            choices.forEach(choice -> {
//                stringBuilder.append(UnicodeUtil.toString(choice.getText()));
//            });
//            StringBuilder s = new StringBuilder(stringBuilder.toString());
//            if (s.toString().contains("\n")) {
//                s = new StringBuilder("<br/>");
//            }
//            return s.toString().replace(" ", "&ensp;");
//        }).cache();
//    }
}
